package com.study.shop.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.study.shop.ShopApplication;
import com.study.shop.common.ShopException;
import com.study.shop.entity.dto.LoginDTO;
import com.study.shop.entity.dto.UserDTO;
import com.study.shop.entity.po.User;
import com.study.shop.mapper.UserMapper;
import com.study.shop.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    @Override
    public String login(LoginDTO loginDTO) {
        String username;
        String password;
        // 1. 健壮性判断
        if (ObjectUtils.isEmpty(loginDTO) || !StringUtils.hasText((username = loginDTO.getUsername())) ||
                !StringUtils.hasText((password = loginDTO.getPassword()))) {
            throw new ShopException("请输入账号或者密码");
        }
        // 2. 判断账号是否正确
        User user = userMapper.getUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new ShopException("账号不存在");
        }
        Digester digester = new Digester(DigestAlgorithm.SHA256);
        if (!digester.digestHex(password).equals(user.getPassword())) {
            throw new ShopException("账号或者密码错误");
        }
        // 3. 账号正确，封装返回信息
        String token = UUID.randomUUID().toString();
        ShopApplication.caches.put(token,user.getUserId().toString());
        return token;
    }

    @Override
    public UserDTO info(String token) {
        String userIdStr = ShopApplication.caches.get(token);
        if (!StringUtils.hasText(userIdStr)) {
            throw new ShopException("token已经过期，请重新登陆");
        }
        Long userId = Long.valueOf(userIdStr);
        UserDTO userDTO = userMapper.getUserDTOById(userId);
        if (ObjectUtils.isEmpty(userDTO)) {
            throw new ShopException("请联系管理员添加用户信息");
        }
        userDTO.setPassword("");
        return userDTO;
    }

    @Override
    public void logout(String token) {
        ShopApplication.caches.remove(token);
    }
}
